package com.ali.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * 自定义服务端处理器
 */
public class MyGroupChatServerHandler extends SimpleChannelInboundHandler<String> {
    private static final DefaultChannelGroup defaultChannelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 通道激活
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        //获取通道
        Channel channel = ctx.channel();
        String message = channel.remoteAddress() + "：上线";
        System.out.println(message);
        //向其他客户端转发
        defaultChannelGroup.writeAndFlush(message);
        //添加客户端
        defaultChannelGroup.add(channel);
    }

    /**
     * 通道读取
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) {
        //获取通道
        Channel channel = channelHandlerContext.channel();
        String message = channel.remoteAddress() + "：" + s;
        System.out.println(message);
        for (Channel tempChannel : defaultChannelGroup) {
            if (channel != tempChannel) {
                //向其他客户端转发
                tempChannel.write(message);
                tempChannel.flush();
            }
        }
    }

    /**
     * 通道非激活
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        //获取通道
        Channel channel = ctx.channel();
        String message = channel.remoteAddress() + "：下线";
        System.out.println(message);
        //向其他客户端转发
        defaultChannelGroup.writeAndFlush(message);
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        //关闭客户端连接
        ctx.close();
    }
}
